<template>

  <div class="container">

    <!-- 按需查询 -->
    <div class="select-scope">
      <el-input
        placeholder="模糊查询题目"
        v-model="question"
        size="small"
        clearable>
      </el-input>

      <el-select v-model="type" placeholder="请选择题型" size="small">
        <el-option
          v-for="item in types"
          :key="item.value"
          :label="item.label"
          :value="item.value">
        </el-option>
      </el-select>

      <el-button icon="el-icon-search" type="success" @click="search" circle size="small"></el-button>
      <el-button type="info" icon="el-icon-refresh" @click="refresh" circle size="small"></el-button>

    </div>

    <!--表格信息-->
    <el-table
      :data="tableData"
      :cell-style="{padding:'2px 0px'}"
      :header-cell-style="{padding:'5px 0px'}"
      style="width: 100%">
      <el-table-column
        prop="type"
        label="题型"
        width="100">
      </el-table-column>
      <el-table-column
        prop="question"
        label="题目内容">
      </el-table-column>
      <el-table-column
        label="操作"
        width="120">
        <template slot-scope="scope">
          <!-- 修改数据 -->
          <el-button type="primary" icon="el-icon-edit" @click="updateShow(scope.row)" circle></el-button>
          <!-- 删除数据 -->
          <el-button type="danger" icon="el-icon-delete" @click="removeQuestion(scope.row)" circle></el-button>
        </template>

      </el-table-column>
    </el-table>

    <!-- 添加按钮 -->
    <div class="add-button">
      <el-button type="primary" icon="el-icon-plus" @click="insertDialogFormVisible = true">添加题目</el-button>
    </div>
    <!-- 新增题目的表单弹窗 -->
    <el-dialog title="添加题目" :visible.sync="insertDialogFormVisible" top="8vh">
      <el-form ref="form" size="mini" :model="insertForm" label-width="80px">
        <el-form-item label="题目">
          <el-input type="textarea" v-model="insertForm.question"></el-input>
        </el-form-item>
        <el-form-item label="题型">
          <el-select v-model="insertForm.type" placeholder="请选择该题目的题型">
            <el-option label="单选题" value="radio"></el-option>
            <el-option label="多选题" value="multi"></el-option>
            <el-option label="判断题" value="judge"></el-option>
          </el-select>
        </el-form-item>
        <!-- 单选和多选 -->
        <div v-if="insertForm.type === 'radio' || insertForm.type === 'multi'">
          <el-form-item label="选项A">
            <el-input v-model="insertForm.optionA"></el-input>
          </el-form-item>
          <el-form-item label="选项B">
            <el-input v-model="insertForm.optionB"></el-input>
          </el-form-item>
          <el-form-item label="选项C">
            <el-input v-model="insertForm.optionC"></el-input>
          </el-form-item>
          <el-form-item label="选项D">
            <el-input v-model="insertForm.optionD"></el-input>
          </el-form-item>
        </div>
        <!-- 答案的选择判断 -->
        <!-- 单选 -->
        <el-form-item label="正确答案" v-if="insertForm.type === 'radio'">
          <el-radio-group v-model="insertForm.answer">
            <el-radio label="A"></el-radio>
            <el-radio label="B"></el-radio>
            <el-radio label="C"></el-radio>
            <el-radio label="D"></el-radio>
          </el-radio-group>
        </el-form-item>
        <!-- 多选 -->
        <el-form-item label="正确答案" v-if="insertForm.type === 'multi'">
          <el-checkbox-group v-model="insertForm.answer">
            <el-checkbox label="A" name="answer"></el-checkbox>
            <el-checkbox label="B" name="answer"></el-checkbox>
            <el-checkbox label="C" name="answer"></el-checkbox>
            <el-checkbox label="D" name="answer"></el-checkbox>
          </el-checkbox-group>
        </el-form-item>
        <!-- 判断题 -->
        <el-form-item label="正确答案" v-if="insertForm.type === 'judge'">
          <el-radio-group v-model="insertForm.answer">
            <el-radio label="A">√</el-radio>
            <el-radio label="B">×</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="insertDialogFormVisible = false">取 消</el-button>
        <el-button type="warning" @click="resetForm">重 置</el-button>
        <el-button type="primary" @click="addQuestion">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 更新题目的表单弹窗 -->
    <el-drawer
      title="更新题目数据"
      :before-close="handleClose"
      :visible.sync="updateDialogFormVisible"
      direction="rtl"
      custom-class="demo-drawer"
      size="40%"
      :close-on-press-escape="false">
      <div class="demo-drawer__content">

        <el-form ref="form" size="small" :model="updateForm" label-width="80px">
          <el-form-item label="题目">
            <el-input type="textarea" v-model="updateForm.question"></el-input>
          </el-form-item>
          <el-form-item label="题型">
            <el-select v-model="updateForm.type" placeholder="请选择该题目的题型">
              <el-option label="单选题" value="radio"></el-option>
              <el-option label="多选题" value="multi"></el-option>
              <el-option label="判断题" value="judge"></el-option>
            </el-select>
          </el-form-item>
          <!-- 单选和多选 -->
          <div v-if="updateForm.type === 'radio' || updateForm.type === 'multi'">
            <el-form-item label="选项A">
              <el-input v-model="updateForm.optionA"></el-input>
            </el-form-item>
            <el-form-item label="选项B">
              <el-input v-model="updateForm.optionB"></el-input>
            </el-form-item>
            <el-form-item label="选项C">
              <el-input v-model="updateForm.optionC"></el-input>
            </el-form-item>
            <el-form-item label="选项D">
              <el-input v-model="updateForm.optionD"></el-input>
            </el-form-item>
          </div>
          <!-- 答案的选择判断 -->
          <!-- 单选 -->
          <el-form-item label="正确答案" v-if="updateForm.type === 'radio'">
            <el-radio-group v-model="updateForm.answer">
              <el-radio label="A"></el-radio>
              <el-radio label="B"></el-radio>
              <el-radio label="C"></el-radio>
              <el-radio label="D"></el-radio>
            </el-radio-group>
          </el-form-item>
          <!-- 多选 -->
          <el-form-item label="正确答案" v-if="updateForm.type === 'multi'">
            <el-checkbox-group v-model="updateForm.answer">
              <el-checkbox label="A" name="update"></el-checkbox>
              <el-checkbox label="B" name="update"></el-checkbox>
              <el-checkbox label="C" name="update"></el-checkbox>
              <el-checkbox label="D" name="update"></el-checkbox>
            </el-checkbox-group>
          </el-form-item>
          <!-- 判断题 -->
          <el-form-item label="正确答案" v-if="updateForm.type === 'judge'">
            <el-radio-group v-model="updateForm.answer">
              <el-radio label="A">√</el-radio>
              <el-radio label="B">×</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-form>

        <div slot="footer" class="dialog-footer" style="text-align: center">
          <el-button @click="updateDialogFormVisible = false">取 消</el-button>
          <el-button type="primary" @click="updateQuestion">更 新</el-button>
        </div>
      </div>
    </el-drawer>

  </div>

</template>

<script>
import { Error, Success, Info, Confirm } from "../../utils/element.config.js";
import { AddQuestion, GetQuestionsBank, UpdateQuestion, DeleteQuestion } from "../../api/public";

export default {
  data() {
    return {
      question: '', // 用于模糊查询
      types: [ // 选择器的按钮数据
        {
          value: 'radio',
          label: '单选题'
        },
        {
          value: 'multi',
          label: '多选题'
        },
        {
          value: 'judge',
          label: '判断题'
        }
      ],
      type: '', // 题型
      tableData: [], // 展示在表格中的数据信息
      questions: {
        'radio': [],
        'multi': [],
        'judge': []
      }, // 所有的题目数据(分类)
      insertDialogFormVisible: false, // 是否显示`添加Dialog`弹窗
      updateDialogFormVisible: false, // 是否显示`修改Dialog`弹窗
      insertForm: { // 添加题目的表单数据
        question: '',
        type: '',
        optionA: '',
        optionB: '',
        optionC: '',
        optionD: '',
        answer: []
      },
      updateForm: {} // 更新题目数据的表单
    }
  },
  created() {
    this.getQuestionsBank();
  },
  methods: {
    /** 刷新表格的按钮 **/
    refresh(){
      this.question = '';
      this.type = '';
      this.tableData =
        this.questions['radio'].concat(this.questions['multi']).concat(this.questions['judge']);
    },
    /** 搜索按钮 **/
    search(){
      /* 判断是否有选中要查找的题型 */
      if( !this.type )
        return Error("请选择搜索的题型");
      let search = [];
      /* 获取相关题型的题目 */
      this.questions[this.type].forEach(item => {
        /* 搜索题目关键词 */
        if( item.question.indexOf(this.question) !== -1 ){
          search.push(item);
        }
      })
      this.tableData = search;
    },
    /** 页面的 修改弹窗 **/
    handleClose(done) {
      if (this.loading)
        return;
      Confirm('确定要关闭表单吗？')
        .then(_ => {
          done();
        })
        .catch(_ => {});
    },
    /** 获取题库数据 **/
    getQuestionsBank(){

      GetQuestionsBank().then(result => {

        if( result.code === 200 ){
          let radio = [];
          let multi = [];
          let judge = [];
          /* 对题目的数据进行处理 */
          result.data.forEach(item => {
            if( item.type === 'radio' ){
              radio.push(item);
            }else if( item.type === 'multi' ){
              multi.push(item);
            }else if( item.type === 'judge' ){
              judge.push(item);
            }
          })

          this.questions = {
            'radio': radio,
            'multi': multi,
            'judge': judge
          }

        }else if( result.code === 300 ){
          Info(result.message)
        }
      })

    },
    /** 表单重置的方法 **/
    resetForm(){
      Confirm('是否重置表单数据', '提示').then(() => {
        this.insertForm = {
          question: '',
          type: '',
          optionA: '',
          optionB: '',
          optionC: '',
          optionD: '',
          answer: []
        }
        Success("表单重置成功")
      }).catch(() => {
        Info("已取消表单重置")
      });
    },
    /** 新增题目的请求 **/
    addQuestion(){

      AddQuestion(this.insertForm).then(result => {
        if( result.code === 200 ){

          this.insertForm['id'] = result.data.id
          this.questions[this.insertForm.type].push(JSON.parse(JSON.stringify(this.insertForm)));
          Success("添加成功");
          /* 请求成功后 */
          this.insertForm = {
            question: '',
            type: '',
            optionA: '',
            optionB: '',
            optionC: '',
            optionD: '',
            answer: []
          }
          /* 将弹窗关闭 */
          this.insertDialogFormVisible = false

        }else if( result.code === 300 ){
          Error(result.message)
        }
      })
    },
    /** 删除题目的请求 **/
    removeQuestion(data){
      Confirm('是否删除该条数据', '提示').then(() => {

        DeleteQuestion({id: data.id}).then(result=>{
          if( result.code === 200 ){
            /* 删除页面上显示的数据 */
            for (let i = 0; i < this.questions[data.type].length; i++){
              if( this.questions[data.type][i].id === data.id )
                this.questions[data.type].splice(i, 1);
            }
            Success("删除成功")
          }else if( result.code === 300 ){
            Error(result.message)
          }
        })

      }).catch(() => {
        Info("已取消表单重置")
      });
    },
    /** 数据修改: 数显 **/
    updateShow(data){
      /* 直接获取数据, 使用深克隆垄断两个数据之间的联系 */
      this.updateForm = JSON.parse(JSON.stringify(data))
      /* 如果时多选题， 那么就把答案手动变成数组 */
      if( this.updateForm.type === 'multi' ){
        if( this.updateForm.answer instanceof Array){}
        else this.updateForm.answer = this.updateForm.answer.split("");
      }
      /* 弹出表单 */
      this.updateDialogFormVisible = true;
    },
    /** 修改题目数据的请求 **/
    updateQuestion(){

      UpdateQuestion(this.updateForm).then(result=>{
        if( result.code === 200 ){
          /* 数据更新到页面上 */
          for( let i = 0; i < this.questions[this.updateForm.type].length; i++ ){
            if( this.updateForm.id === this.questions[this.updateForm.type][i].id )
              this.questions[this.updateForm.type][i] = JSON.parse(JSON.stringify(this.updateForm))
          }
          this.tableData =
            this.questions['radio'].concat(this.questions['multi']).concat(this.questions['judge']);
          Success("修改成功");
          /* 将弹窗关闭 */
          this.updateDialogFormVisible = false
        }else if( result.code === 300 ){
          Error(result.message)
        }
      })

    }
  },
  computed: {
    /* 使用计算机属性来监听下面的值变化, 谁的值进行变化了就调用一次该方法 */
    questionsListener: function(){
      let _arr = []
      _arr.push(this.questions.radio.length)
      _arr.push(this.questions.multi.length)
      _arr.push(this.questions.judge.length)
      return _arr.join(",")
    }
  },
  watch: { // 监听属性
    /** 监听题型属性的变化, 如果切换成 multi, 就把 answer属性变成 数组 **/
    'insertForm.type': function(newTest, oldTest){
      if( newTest === 'multi')
        this.insertForm.answer = [];
      if( newTest === 'judge' ){
        this.insertForm.optionA = '√';
        this.insertForm.optionB = '×';
      }
      if( oldTest === 'judge' ){
        this.insertForm.optionA = '';
        this.insertForm.optionB = '';
      }
    },
    'updateForm.type': function(newTest, oldTest){
      if( newTest === 'multi' && oldTest )
        this.updateForm.answer = [];
      if( newTest === 'judge' ){
        this.updateForm.optionA = '√';
        this.updateForm.optionB = '×';
      }
      if( oldTest === 'judge' ){
        this.updateForm.optionA = '';
        this.updateForm.optionB = '';
      }
    },
    updateDialogFormVisible: function(newTest){
      if( !newTest ) // 如果更新数据的弹窗关闭了, 那么就清空表单数据
        this.updateForm = {}
    },
    /** 监听 Computed属性中的 questionsListener 方法, 如果变化了, 那么就调用该方法 **/
    questionsListener(){
      this.tableData =
        this.questions['radio'].concat(this.questions['multi']).concat(this.questions['judge']);
    }
  }
}
</script>

<style scoped>
.select-scope{
  margin-bottom: 10px;
}
.select-scope .el-input, .el-select{
  margin-right: 10px;
  width: 175px;
}
.container{
  position: relative;
}
.add-button{
  position: absolute;
  top: 0;
  right: 1px;
  width: 120px;
}
.add-button .el-button{
  padding: 8px 22px;
}
</style>
